from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba
import pandas as pd

# 解决中文显示和负号问题
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
plt.rcParams["axes.unicode_minus"] = False


def catering_word_cloud_demo():
    # 读取Excel数据（文件路径按实际设置）
    file_path = r'餐饮连锁品牌数据.xlsx'
    dishes_df = pd.read_excel(file_path, sheet_name='菜品信息')

    # 数据清洗：过滤菜品名称为空的记录，提取所有菜品名称
    dishes_df = dishes_df.dropna(subset=['菜品名称'])
    chinese_text = ' '.join(dishes_df['菜品名称'].tolist())

    # 中文分词（保留有意义的词汇，过滤无意义助词）
    seg_list = jieba.cut(chinese_text, cut_all=False)
    # 自定义停用词（结合餐饮场景补充无意义词汇）
    stopwords = {"的", "是", "可以", "一种", "那些", "一些", "任何", "这样", "如此", "通过", "直接", "有关", "原因",
                 "方式", "觉得", "操作", "现在", "今天", "一直", "基本", "可能", "部分", "全部", "他们", "她的", "他的",
                 "这个", "那个", "这些", "那些", "怎么", "如何", "什么", "哪里", "多少", "时候", "时间", "组织", "等级",
                 "电子", "行业", "方面", "生活", "程序", "国家", "用户", "社区", "免费", "评论", "记者", "问题", "环境",
                 "工程", "学习", "文化", "生产", "增加", "出来", "系列", "而且", "法律", "发表", "研究", "大家", "东西",
                 "个人", "之间", "全国", "北京", "帮助", "显示", "拥有", "一定", "实现", "更多", "业务", "欢迎", "以后",
                 "历史", "目前", "一直", "注意", "类别", "功能", "不要", "我们", "以后", "喜欢", "不会", "还有", "提高",
                 "相关", "这个", "一直"}
    seg_text = " ".join([word for word in seg_list if word not in stopwords and len(word) > 1])

    # 中文字体路径（Windows系统默认路径，Mac/Linux需修改为对应字体路径）
    font_path = "C:\\WINDOWS\\Fonts\\MSYH.TTC"  # Mac可改为："/System/Library/Fonts/PingFang.ttc"；Linux可改为："/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc"

    # 创建中文词云对象（优化参数适配餐饮数据）
    wc = WordCloud(
        font_path=font_path,
        background_color="white",
        width=1000,
        height=800,
        max_words=150,
        font_step=2,
        random_state=42,
        collocations=False,  # 避免重复词组
        prefer_horizontal=0.7  # 70%水平显示
    ).generate(seg_text)

    # 显示并保存词云图
    plt.figure(figsize=(12, 10), dpi=100)
    plt.imshow(wc, interpolation='bilinear')  # 优化图像平滑度
    plt.axis("off")
    plt.title("餐饮连锁品牌菜品名称关键词词云", fontsize=18, fontweight='bold', pad=30)
    plt.tight_layout()
    # 保存图片到当前文件夹
    plt.savefig(r'菜品名称词云图.png', dpi=150, bbox_inches='tight', facecolor='white')
    plt.show()


# 调用函数生成词云
catering_word_cloud_demo()

# 输出关键词频次统计（辅助分析）
print("菜品名称高频关键词TOP10：")
word_count = {}
for word in seg_text.split():
    word_count[word] = word_count.get(word, 0) + 1
sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:10]
for word, count in sorted_words:
    print(f"{word}: {count}次")